package cn.com.dhcc.ddi.stat.controller;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.service.CmUserMgrService;
import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.vo.UserInfoVo;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.ddi.datamapping.service.DataMappingService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.pub.core.util.dateformatter.DateFormatter;
import cn.com.dhcc.app.pub.core.util.echarts.BarChartVo;
import cn.com.dhcc.app.pub.core.util.echarts.ElementStyle;
import cn.com.dhcc.app.pub.core.util.echarts.ItemStyle;
import cn.com.dhcc.app.pub.core.util.echarts.SeriesVo;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Categories;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Category;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartDataset;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartSet;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartXmlUtil;
import cn.com.dhcc.ddi.stat.service.TaskSyncStatService;
import cn.com.dhcc.ddi.stat.vo.TaskSyncStatVo;

import javax.servlet.http.HttpSession;

/**
 * 
    * @ClassName: TaskSyncStatisticsController
    * @date 2017-3-10
    *
 */
@Controller
@RequestMapping("/stat")
public class TaskSyncStatisticsController extends BaseController {

	Logger logger = Log.getLogger(LOGTYPE.ADAPTER);
	
	@Autowired
	private TaskSyncStatService taskSyncStatService;
	@Autowired
	DataMappingService dataMappingService;
	@Autowired
	CmUserMgrService userMgrService;
	/**
	 * 获取列表
	    * @Title: list
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @param model
	    * @param @param pager
	    * @param @param name
	    * @param @param orderName
	    * @param @param order
	    * @param @return    参数
	    * @return String    返回类型
	    * @throws
	 */
	@RequestMapping(value = "/taskSyncStat_info_list")
	public String list(Model model, Pager pager, String taskName, String statDate, String dateScope,HttpSession httpSession) {
		try {
			/*WhereCondition searchData = new WhereCondition();
			if (StrUtil.isNotBlank(taskName)) {
				searchData.where().like("taskName", "%"+taskName+"%");
			}
			if (StrUtil.isNotBlank(statDate)) {
				searchData.and().like("t1.stat_date","%"+statDate+"%");
			}
			if (StrUtil.isNotBlank(orderName)) {
				searchData.orderBy(orderName + " " + order);
			} else {
				searchData.orderBy("stat_date  desc");
			}
			PagerData<TaskSyncStatVo> datas = taskSyncStatService.list(pager, searchData);*/
			
			int s = 0;
			if(dateScope != null) {
				s = Integer.parseInt(dateScope);
			}
			
			if(statDate == null) {
				statDate = DateFormatter.getDateBasedOnToday("yyyy-MM-dd", -1);
			}
			
			WhereCondition condition = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			if(!isAdmin){
				UserInfoVo currentUser = userMgrService.getUserById(userId);
				if(currentUser != null){
					String nodeIdsStr = currentUser.getExt2();
					WhereCondition dmParameter = new WhereCondition();
					dmParameter.where();
					if(StrUtil.isNotBank(nodeIdsStr)){
						String[] nodeIds = nodeIdsStr.split(",");
						dmParameter.in("t2.node_id", nodeIds);
						dmParameter.andIn("t3.node_id", nodeIds);
					}else{
						dmParameter.eq("1", "2");
					}
					List<String> dmids = dataMappingService.getDmid(dmParameter);
					//过滤用户数据
					if (dmids!=null && dmids.size()>0){
						condition.and().in("t3.mp_id",dmids);
					}else {
						condition.and().eq("1","2");
					}
				}
			}
			PagerData<TaskSyncStatVo> taskPagerData = taskSyncStatService.getTaskStatPagerData(pager, condition, s, statDate);
			
			model.addAttribute("List", taskSyncStatService.getTasks());
			model.addAttribute(DATA_KEY, taskPagerData.getDatas());
			setTotoal(model, taskPagerData.getTotal());
			return "stat/taskSyncStat_list";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}
	
	/**
	 * 转到各任务数据量统计图页面
	 * @param 
	 * @return
	 * @throws 
	 */
	@RequestMapping("/task_syn_stat")
	public String recSentChart() {
		return "stat/task_syn_stat";
	}
	
	/**
	 * 获取统计图需要的数据量数据
	 * @param ptaskId
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping(value="/get_taskSyn", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> generateSynData(int dateScope, int dataScope, String date,HttpSession httpSession) {
		try {
			WhereCondition taskParameter = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			if(!isAdmin){
				UserInfoVo currentUser = userMgrService.getUserById(userId);
				if(currentUser != null){
					String nodeIdsStr = currentUser.getExt2();
					WhereCondition dmParameter = new WhereCondition();
					dmParameter.where();
					if(StrUtil.isNotBank(nodeIdsStr)){
						String[] nodeIds = nodeIdsStr.split(",");
						dmParameter.in("t2.node_id", nodeIds);
						dmParameter.andIn("t3.node_id", nodeIds);
					}else{
						dmParameter.eq("1", "2");
					}
					List<String> dmids = dataMappingService.getDmid(dmParameter);
					//过滤用户数据
					if (dmids!=null && dmids.size()>0){
						taskParameter.and().in("t2.mp_id",dmids);
					}else {
						taskParameter.and().eq("1","2");
					}
				}
			}
			taskParameter.groupBy("task_id");
			List<TaskSyncStatVo> tasks = taskSyncStatService.getTaskStatData(taskParameter,dateScope, date);
			
			//set categories
			List<String> categories = new ArrayList<String>();
			for(TaskSyncStatVo vo: tasks) {
				categories.add(vo.getTaskName());
			}
			
			String cateName = "";
			if(dataScope == 0) {
				cateName = "频次";
			} else {
				cateName = "数据量";
			}
			
			String caption = date + " ETL任务执行" + cateName;
			
			//data
			List<SeriesVo> series = new ArrayList<SeriesVo>();
			SeriesVo mySeries = new SeriesVo();
			if(dataScope == 0){
				mySeries.setName("同步频率");
			}else {
				mySeries.setName("数据量");
			}
			
			mySeries.setType("bar");
			mySeries.setBarMaxWidth("40");
			
			//label
			/*LabelStyle myLabelStyle = new LabelStyle();
			myLabelStyle.setTextStyle(new TextStyle("#428BCA"));
			SeriesLabel myLabel = new SeriesLabel();
			myLabel.setNormal(myLabelStyle);*/
			ItemStyle myItemStyle = new ItemStyle();
			myItemStyle.setNormal(new ElementStyle("#428BCA"));
			mySeries.setItemStyle(myItemStyle);
		
			List<String> values = new ArrayList<String>();
			if(dataScope == 0) {
				for(TaskSyncStatVo vo: tasks) {
					values.add(""+vo.getTotal());
				}
			} else {
				for(TaskSyncStatVo vo: tasks) {
					values.add(""+vo.getDataSize());
				}
			}
			mySeries.setData(values);
			series.add(mySeries);
			
			BarChartVo chartData = new BarChartVo(caption, series, categories);
				
			return jsonSuccessDataResult("获取统计图", chartData);
		} catch(ServiceException e) {
			logger.error(e);
			return jsonFailResult("获取统计图失败");
		}
	}
	
	/*@RequestMapping(value="/task_chart_data", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> generateTaskData(int dateScope, int dataScope, String date) {
		try {			
			List<TaskSyncStatVo> tasks = taskSyncStatService.getTaskStatData(dateScope, date);
			
			//set categories
			List<String> categories = new ArrayList<String>();
			for(TaskSyncStatVo vo: tasks) {
				categories.add(vo.getTaskName());
			}
			
			String cateName = "";
			if(dataScope == 0) {
				cateName = "频次";
			} else {
				cateName = "数据量";
			}
			
			String caption = date + " ETL任务执行" + cateName;
			
			//data
			List<String> values = new ArrayList<String>();
			if(dataScope == 0) {
				for(TaskSyncStatVo vo: tasks) {
					values.add(""+vo.getTotal());
				}
			} else {
				for(TaskSyncStatVo vo: tasks) {
					values.add(""+vo.getDataSize());
				}
			}
			
			BarChartVo chartData = new BarChartVo(caption, values, categories);
				
			return jsonSuccessDataResult("获取统计图", chartData);
		} catch(ServiceException e) {
			logger.error(e);
			return jsonFailResult("获取统计图失败");
		}
	}*/
	
	/**
	 * 获取统计图需要的频次数据
	 * @param ptaskId
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping(value="/get_taskTotal", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> generateTotalData(String scope, String date) {
		//返回的xml
		Map<String,Object> output = new HashMap<String, Object>();		
		
		//set categories
		Categories cate = new Categories();
		try {
			List<Category> cList = new ArrayList<Category>();
			List<String> names = taskSyncStatService.getTaskNames();
			for(String name:names) {
				cList.add(new Category(name));
			}
			cate.setCategory(cList);
		} catch (ServiceException e) {
			logger.error(e);
		}

		ChartDataset totalDataSet = new ChartDataset("同步频次");
		totalDataSet.setColor("7FFFAA");
		
		List<String> ids = new ArrayList<String>();
		try {
			ids = taskSyncStatService.getTaskId();
		} catch (ServiceException e) {
			logger.error(e);
		}
		
		int s = 0;
		try {
			s = Integer.parseInt(scope);
		} catch (NumberFormatException e) {
			logger.error(e);
		}
		
		//频次
		List<ChartSet> totalList = new ArrayList<ChartSet>();
		try {
			Map<String, String> synMap = taskSyncStatService.getSynTotalCount(s, date);
			
			//按顺序添加值
			for(String id: ids) {
				totalList.add(new ChartSet(synMap.get(id)));
			}
		} catch (ServiceException e) {
			logger.error(e);
		}
		totalDataSet.setSet(totalList);
		
		//add values to chart
		List<ChartDataset> totalSetList = new ArrayList<ChartDataset>();
		//dataSetList.add(synDataSet);
		totalSetList.add(totalDataSet);
		//generate xml file	
		output.put("chart", ChartXmlUtil.getXmlForColumn("ETL任务执行频次", cate, totalSetList, ""));
		
		return output;	
	}
	
}